﻿using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders.Physical;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;

namespace Orchid.Blazor.Hosting.Repositories
{
    /// <summary>
    /// 基于目录的 <inheritdoc cref="WebRepository"/>
    /// </summary>
    public class WebDirectoryRepository : WebRepository
    {
        IFileProvider _webRootFileProvider;

        /// <summary>
        /// 目录。
        /// </summary>
        public DirectoryInfo Directory { get; }
        /// <inheritdoc/>
        public override string Name { get; }

        /// <summary>
        /// <inheritdoc cref="WebDirectoryRepository"/>
        /// </summary>
        /// <param name="directory"><inheritdoc cref="Directory" path="//summary"/></param>
        public WebDirectoryRepository(DirectoryInfo directory) : this(directory, isRoot: false) { }
        internal WebDirectoryRepository(DirectoryInfo directory, bool isRoot)
        {
            this.Directory = directory ?? throw new ArgumentNullException(nameof(directory));
            this.Path = this.Directory.FullName;
            if (!isRoot) this.Name = this.Directory.Name;
            var dir = new DirectoryInfo(System.IO.Path.Combine(this.Directory.FullName, ContentDirectoryName));
            _webRootFileProvider = dir.Exists ? new PhysicalFileProvider(dir.FullName, ExclusionFilters.None) : new PhysicalFileProvider(this.Directory.FullName, ExclusionFilters.None);
        }

        /// <inheritdoc/>
        public override IDirectoryContents GetDirectoryContents(string subpath) => _webRootFileProvider.GetDirectoryContents(subpath);
        /// <inheritdoc/>
        protected override IFileInfo GetFile(string subpath) => _webRootFileProvider.GetFileInfo(subpath);
        /// <inheritdoc/>
        public override IChangeToken Watch(string filter) => _webRootFileProvider.Watch(filter);

        /// <inheritdoc/>
        public override void Dispose()
        {
            (_webRootFileProvider as IDisposable)?.Dispose();

            base.Dispose();
        }

        /// <summary>
        /// 获取网站仓库集。
        /// </summary>
        /// <param name="directory">目录。</param>
        /// <returns>获取到的网站仓库集合。</returns>
        public static IEnumerable<WebDirectoryRepository> GetRepostories(DirectoryInfo directory)
        {
            var res = new List<WebDirectoryRepository>();
            if (directory == null) return res;
            if (!directory.Exists) return res;
            var directories = directory.GetDirectories();
            foreach(var dir in directories)
            {
                if (string.Equals(dir.Name, ContentDirectoryName, StringComparison.OrdinalIgnoreCase)) continue;
                res.Add(new WebDirectoryRepository(dir));
            }
            return res;
        }
    }
}
